package com.zzptc.sky.baidudemo.utils;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;

import com.zzptc.sky.baidudemo.adapter.BoxAdapter;
import com.zzptc.sky.baidudemo.vo.BaiBoxInfo;

import java.util.Collections;
import java.util.List;

/**
 * Created by Administrator on 2017/5/25.
 */

public class BoxCallBack extends ItemTouchHelper.Callback {

    private BoxAdapter mAdapter;
    private List<BaiBoxInfo> datas;

    public BoxCallBack(BoxAdapter mAdapter, List<BaiBoxInfo> datas) {
        this.mAdapter = mAdapter;
        this.datas = datas;
    }


    //设置是否滑动时间，以及拖拽的方向
    //所以在这里需要判断一下是列表布局还是网格布局，如果是列表布局的话则拖拽方向为DOWN和UP，如果是网格布局的话则是DOWN和UP和LEFT和RIGHT
    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
            final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
                    ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            final int swipeFlags = 0;
            return makeMovementFlags(dragFlags, swipeFlags);
        } else {
            final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            final int swipeFlags = 0;
            return makeMovementFlags(dragFlags, swipeFlags);
        }
    }

    //拖动的时候不断回调的方法
    //在这里我们需要将正在拖拽的item和集合的item进行交换元素，然后在通知适配器更新数据
    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        //得到当拖拽的viewHolder的Position
        int fromPosition = viewHolder.getAdapterPosition();
        //拿到当前拖拽到的item的viewHolder
        int toPosition = target.getAdapterPosition();
        if (fromPosition < toPosition) {
            for (int i = fromPosition; i < toPosition; i++) {
                Collections.swap(datas, i, i + 1);
            }
        } else {
            for (int i = fromPosition; i > toPosition; i--) {
                Collections.swap(datas, i, i - 1);
            }
        }
        mAdapter.notifyItemMoved(fromPosition, toPosition);
        return true;
    }


    //替换后调用的方法
    //我们希望在拖拽的时候将被拖拽的Item高亮，这样用户体验要好很多，
    // 所以我们要重写CallBack对象中的onSelectedChanged（）和clearView（）方法，在选中的时候设置高亮背景色，在完成的时候移除高亮背景色
    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

    }
}
